<script setup lang="ts">
import { nextTick, ref, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useElementBounding } from '@vueuse/core';
import { PageTab } from '@sa/materials';
import BetterScroll from '@/components/custom/better-scroll.vue';
import { useAppStore } from '@/store/modules/app';
import { useThemeStore } from '@/store/modules/theme';
import { useRouteStore } from '@/store/modules/route';
import { useTabStore } from '@/store/modules/tab';
import { isPC } from '@/utils/agent';
import DarkModeContainer from '@/components/common/dark-mode-container.vue';
import ReloadButton from '@/components/common/reload-button.vue';
import FullScreen from '@/components/common/full-screen.vue';
import SvgIcon from '@/components/custom/svg-icon.vue';
import ContextMenu from './context-menu.vue';

defineOptions({ name: 'ClientTab' });

const route = useRoute();
const router = useRouter();
const appStore = useAppStore();
const themeStore = useThemeStore();
const routeStore = useRouteStore();
const tabStore = useTabStore();

// 客户端标签系统
const clientTabs = ref<App.Global.Tab[]>([]);
const activeClientTabId = ref('');

// 获取路由标题和图标
function getRouteInfo(path: string) {
  // 这里根据路径匹配不同的标题和图标
  const routeMap: Record<string, { title: string; icon: string }> = {
    '/client/home': { title: '客户端首页', icon: 'mdi:home' },
    '/client/function/test': { title: '测试页面', icon: 'mdi:test-tube' },
    '/client/message': { title: '消息中心', icon: 'mdi:message' },
    '/client/help': { title: '帮助中心', icon: 'mdi:help-circle' }
  };

  // 对于嵌套路由处理
  const matchedRoute = Object.keys(routeMap).find(key => path.startsWith(key));
  if (matchedRoute) {
    return routeMap[matchedRoute];
  }
  
  // 默认
  return { title: '客户端页面', icon: 'mdi:page-layout-body' };
}

// 添加客户端标签
function addClientTab(route: any) {
  const path = route.path;
  
  // 只处理客户端路由
  if (!path.startsWith('/client')) {
    return;
  }
  
  // 检查标签是否已存在
  const existingTab = clientTabs.value.find(tab => tab.path === path);
  if (existingTab) {
    activeClientTabId.value = existingTab.id;
    return;
  }
  
  // 获取路由信息
  const { title, icon } = getRouteInfo(path);
  
  // 创建新标签
  const newTab: App.Global.Tab = {
    id: `client-${Date.now()}`,
    label: title,
    path,
    routeKey: route.name as string,
    icon,
    closable: path !== '/client/home' // 首页不可关闭
  };
  
  clientTabs.value.push(newTab);
  activeClientTabId.value = newTab.id;
}

// 切换标签
function switchTab(tab: App.Global.Tab) {
  router.push(tab.path);
  activeClientTabId.value = tab.id;
}

// 关闭标签
async function handleCloseTab(tab: App.Global.Tab) {
  const index = clientTabs.value.findIndex(t => t.id === tab.id);
  if (index === -1) return;
  
  // 如果关闭的是激活的标签，则需要激活其他标签
  const isActiveTab = tab.id === activeClientTabId.value;
  
  clientTabs.value.splice(index, 1);
  
  if (isActiveTab && clientTabs.value.length > 0) {
    // 优先激活右侧标签，没有则激活左侧标签
    const targetIndex = Math.min(index, clientTabs.value.length - 1);
    switchTab(clientTabs.value[targetIndex]);
  }
}

const bsWrapper = ref<HTMLElement>();
const { width: bsWrapperWidth, left: bsWrapperLeft } = useElementBounding(bsWrapper);
const bsScroll = ref<InstanceType<typeof BetterScroll>>();
const tabRef = ref<HTMLElement>();
const isPCFlag = isPC();

const TAB_DATA_ID = 'data-tab-id';

type TabNamedNodeMap = NamedNodeMap & {
  [TAB_DATA_ID]: Attr;
};

async function scrollToActiveTab() {
  await nextTick();
  if (!tabRef.value) return;

  const { children } = tabRef.value;

  for (let i = 0; i < children.length; i += 1) {
    const child = children[i];

    const { value: tabId } = (child.attributes as TabNamedNodeMap)[TAB_DATA_ID];

    if (tabId === activeClientTabId.value) {
      const { left, width } = child.getBoundingClientRect();
      const clientX = left + width / 2;

      setTimeout(() => {
        scrollByClientX(clientX);
      }, 50);

      break;
    }
  }
}

function scrollByClientX(clientX: number) {
  const currentX = clientX - bsWrapperLeft.value;
  const deltaX = currentX - bsWrapperWidth.value / 2;

  if (bsScroll.value?.instance) {
    const { maxScrollX, x: leftX, scrollBy } = bsScroll.value.instance;

    const rightX = maxScrollX - leftX;
    const update = deltaX > 0 ? Math.max(-deltaX, rightX) : Math.min(-deltaX, -leftX);

    scrollBy(update, 0, 300);
  }
}

async function refresh() {
  appStore.reloadPage(500);
}

interface DropdownConfig {
  visible: boolean;
  x: number;
  y: number;
  tabId: string;
}

const dropdown = ref<DropdownConfig>({
  visible: false,
  x: 0,
  y: 0,
  tabId: ''
});

function setDropdown(config: Partial<DropdownConfig>) {
  Object.assign(dropdown.value, config);
}

let isClickContextMenu = false;

function handleDropdownVisible(visible: boolean | undefined) {
  if (!isClickContextMenu) {
    setDropdown({ visible });
  }
}

async function handleContextMenu(e: MouseEvent, tabId: string) {
  // 不允许对首页使用右键菜单
  const tab = clientTabs.value.find(t => t.id === tabId);
  if (tab && tab.path === '/client/home') return;
  
  e.preventDefault();

  const { clientX, clientY } = e;

  isClickContextMenu = true;

  const DURATION = dropdown.value.visible ? 150 : 0;

  setDropdown({ visible: false });

  setTimeout(() => {
    setDropdown({
      visible: true,
      x: clientX,
      y: clientY,
      tabId
    });
    isClickContextMenu = false;
  }, DURATION);
}

function getContextMenuDisabledKeys(tabId: string) {
  const disabledKeys: App.Global.DropdownKey[] = [];
  
  // 找到对应标签
  const tab = clientTabs.value.find(t => t.id === tabId);
  
  // 禁用首页相关操作
  if (tab && tab.path === '/client/home') {
    disabledKeys.push('closeCurrent', 'closeLeft', 'closeAll');
  }
  
  return disabledKeys;
}

// 清除所有标签（保留首页）
function clearAllTabs() {
  const homeTabs = clientTabs.value.filter(tab => tab.path === '/client/home');
  clientTabs.value = homeTabs;
  if (homeTabs.length > 0) {
    switchTab(homeTabs[0]);
  }
}

// 清除左侧标签（保留首页）
function clearLeftTabs(currentId: string) {
  const currentIndex = clientTabs.value.findIndex(tab => tab.id === currentId);
  if (currentIndex <= 0) return;
  
  // 保留首页和当前标签右侧标签
  const homeTabs = clientTabs.value.filter(tab => tab.path === '/client/home');
  const rightTabs = clientTabs.value.slice(currentIndex);
  
  clientTabs.value = [...homeTabs, ...rightTabs];
}

// 清除右侧标签
function clearRightTabs(currentId: string) {
  const currentIndex = clientTabs.value.findIndex(tab => tab.id === currentId);
  if (currentIndex === -1 || currentIndex === clientTabs.value.length - 1) return;
  
  clientTabs.value = clientTabs.value.slice(0, currentIndex + 1);
}

// 清除其他标签（保留首页和当前标签）
function clearOtherTabs(currentId: string) {
  const currentTab = clientTabs.value.find(tab => tab.id === currentId);
  const homeTabs = clientTabs.value.filter(tab => tab.path === '/client/home');
  
  if (!currentTab) return;
  
  if (currentTab.path === '/client/home') {
    clientTabs.value = homeTabs;
  } else {
    clientTabs.value = [...homeTabs, currentTab];
  }
}

// 提供操作给上下文菜单
const dropdownAction: Record<App.Global.DropdownKey, (tabId: string) => void> = {
  closeCurrent(tabId) {
    const tab = clientTabs.value.find(t => t.id === tabId);
    if (tab) handleCloseTab(tab);
  },
  closeOther(tabId) {
    clearOtherTabs(tabId);
  },
  closeLeft(tabId) {
    clearLeftTabs(tabId);
  },
  closeRight(tabId) {
    clearRightTabs(tabId);
  },
  closeAll() {
    clearAllTabs();
  }
};

function handleDropdown(key: App.Global.DropdownKey) {
  dropdownAction[key]?.(dropdown.value.tabId);
  setDropdown({ visible: false });
}

function removeFocus() {
  (document.activeElement as HTMLElement)?.blur();
}

// 初始化客户端标签页
function initClientTabs() {
  // 添加首页标签
  const homeInfo = getRouteInfo('/client/home');
  const homeTab: App.Global.Tab = {
    id: 'client-home',
    label: homeInfo.title,
    path: '/client/home',
    routeKey: 'client_home',
    icon: homeInfo.icon,
    closable: false // 首页不可关闭
  };
  
  clientTabs.value = [homeTab];
  
  // 如果当前路由是客户端路由，添加当前路由标签
  if (route.path.startsWith('/client') && route.path !== '/client/home') {
    addClientTab(route);
  } else {
    // 否则激活首页标签
    activeClientTabId.value = homeTab.id;
  }
}

// 监听路由变化，添加标签
watch(() => route.path, (newPath) => {
  if (newPath.startsWith('/client')) {
    addClientTab(route);
  }
});

// 监听激活标签ID变化，滚动到激活标签
watch(() => activeClientTabId.value, () => {
  scrollToActiveTab();
});

// 组件挂载后初始化
onMounted(() => {
  initClientTabs();
});
</script>

<template>
  <DarkModeContainer class="size-full flex-y-center px-16px shadow-tab">
    <div ref="bsWrapper" class="h-full flex-1-hidden">
      <BetterScroll ref="bsScroll" :options="{ scrollX: true, scrollY: false, click: !isPCFlag }" @click="removeFocus">
        <div
          ref="tabRef"
          class="h-full flex pr-18px"
          :class="[themeStore.tab.mode === 'chrome' ? 'items-end' : 'items-center gap-12px']"
        >
          <PageTab
            v-for="tab in clientTabs"
            :key="tab.id"
            :[TAB_DATA_ID]="tab.id"
            :mode="themeStore.tab.mode"
            :dark-mode="themeStore.darkMode"
            :active="tab.id === activeClientTabId"
            :active-color="themeStore.themeColor"
            :closable="tab.closable"
            @click="switchTab(tab)"
            @close="handleCloseTab(tab)"
            @contextmenu="handleContextMenu($event, tab.id)"
          >
            <template #prefix>
              <SvgIcon :icon="tab.icon" class="inline-block align-text-bottom text-16px" />
            </template>
            <div class="max-w-240px ellipsis-text">{{ tab.label }}</div>
          </PageTab>
        </div>
      </BetterScroll>
    </div>
    <div>
      <ReloadButton :loading="!appStore.reloadFlag" @click="refresh" />
    </div>
    <FullScreen :full="appStore.fullContent" @click="appStore.toggleFullContent" />
  </DarkModeContainer>
  <ContextMenu
    :visible="dropdown.visible"
    :tab-id="dropdown.tabId"
    :disabled-keys="getContextMenuDisabledKeys(dropdown.tabId)"
    :x="dropdown.x"
    :y="dropdown.y"
    @update:visible="handleDropdownVisible"
    @command="handleDropdown"
  />
</template>

<style scoped></style> 